package com.ruoyi.fire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.fire.domain.DGatewayMessage;
import com.ruoyi.fire.domain.dto.UplinkDataDTO;
import com.ruoyi.fire.mapper.DGatewayMessageMapper;
import com.ruoyi.fire.service.IDGatewayMessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @PackageName: com.iot.fire.service.impl
 * @ClassName: DGatewayMessageServiceImpl
 * @Description:
 * @Author: czl
 * @Date: 2025/11/10 22:56
 */
@Service
@RequiredArgsConstructor
public class DGatewayMessageServiceImpl extends ServiceImpl<DGatewayMessageMapper, DGatewayMessage> implements IDGatewayMessageService {

    /**
     * 根据设备编号查询列表
     * @param deviceNo 设备编码
     * @return
     */
    @Override
    public List<DGatewayMessage> selectByDeviceNo(String deviceNo) {
        LambdaQueryWrapper<DGatewayMessage> wrapper = Wrappers.lambdaQuery(DGatewayMessage.class);
        wrapper.eq(DGatewayMessage::getSN, deviceNo).last("limit 1");
        wrapper.orderByDesc(DGatewayMessage::getTime);
        return list(wrapper);
    }


    /**
     * 根据设备编号查询列表
     * @param deviceNo 设备编码
     * @return
     */
    @Override
    public DGatewayMessage selectLastOneByDeviceNo(String deviceNo) {
        LambdaQueryWrapper<DGatewayMessage> wrapper = Wrappers.lambdaQuery(DGatewayMessage.class);
        wrapper.eq(DGatewayMessage::getSN, deviceNo).last("limit 1");
        wrapper.orderByDesc(DGatewayMessage::getTime);
        return getOne(wrapper);
    }

    /**
     * 根据设备编号查询列表
     * @param gatewayDeviceNos 设备编码
     * @return
     */
    @Override
    public List<DGatewayMessage> selectLastOneByDeviceNos(Set<String> gatewayDeviceNos) {
        LambdaQueryWrapper<DGatewayMessage> wrapper = Wrappers.lambdaQuery(DGatewayMessage.class);
        wrapper.in(DGatewayMessage::getSN, gatewayDeviceNos);
        wrapper.last("GROUP BY SN ORDER BY TIME DESC");
        return list(wrapper);
    }

    /**
     * 设备上行数据
     * @param uplinkDataDTO 设备编号
     * @return
     */
    @Override
    public Page<DGatewayMessage> uplinkData(UplinkDataDTO uplinkDataDTO) {
        LambdaQueryWrapper<DGatewayMessage> wrapper = Wrappers.lambdaQuery(DGatewayMessage.class);
        wrapper.eq(StringUtils.isNotEmpty(uplinkDataDTO.getDeviceNo()),DGatewayMessage::getSN, uplinkDataDTO.getDeviceNo());
        wrapper.orderByDesc(DGatewayMessage::getTime);
        return page(uplinkDataDTO.build(),wrapper);
    }
}
